import React, { useCallback, useEffect } from 'react';
import { Drawer, Button, Form, Input, Select, TreeSelect, message } from 'antd';
import { omit } from 'lodash-es';
import useEnum from '@/hooks/useEnum';
import { batchAddPositions, updatePosition } from '../../services';
import { ACTIONS } from '../../constants';
import useOrgTreeSelect from '@/hooks/useOrgTreeSelect';

// 获得字符串实际长度，中文 2，英文 1
function transformStringLength(str) {
  const len = str.length;
  let lengthStr = '';
  let charCode = -1;
  for (let i = 0; i < len; i++) {
    charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      lengthStr += 'a';
    } else {
      lengthStr += 'bc';
    }
  }
  return lengthStr;
}

const { Option } = Select;

function getModeTitle(mode) {
  switch (mode) {
    case ACTIONS.ADD:
      return '添加岗位';
    case ACTIONS.EDIT:
      return '编辑岗位';
    case ACTIONS.PREVIEW:
      return '查看岗位';
    default:
      // 默认返回null
      console.warn(`未知模式：${mode}`);
      return null;
  }
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const PositionModifyDrawer = ({ position = {}, mode, onClose, reloadParent, visible }) => {
  const [treeData, handleTreeDataLoad] = useOrgTreeSelect();
  const dataSourceEnum = useEnum('500');
  const [form] = Form.useForm();

  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();
    try {
      const values = await form.validateFields();
      const paramsWithoutOrg = omit(values, ['orgId', 'orgName']);
      if (mode === ACTIONS.ADD) {
        const params = { ...paramsWithoutOrg, orgIdList: (values.orgId || []).map(item => item.value) };
        const { code, message: msg } = await batchAddPositions(params);
        if (code === 0) {
          if (msg) {
            message.info(msg);
          }
          reloadParent();
          onClose();
        }
      } else if (mode === ACTIONS.EDIT) {
        const { code } = await updatePosition({ ...position, ...paramsWithoutOrg });
        if (code === 0) {
          reloadParent();
          onClose();
        }
      }
      // reloadParent();
      // onClose();
    } catch (err) {
      console.error(err);
    }
  }, [form, mode, onClose, reloadParent, position]);

  useEffect(() => {
    if (!visible) {
      form.resetFields(['name', 'isPrimary', 'orgId', 'dataSource', 'description']);
    }
  }, [visible, form]);

  return (
    <Drawer
      title={getModeTitle(mode)}
      width={600}
      placement="right"
      onClose={onClose}
      visible={visible}
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={onClose} style={{ marginRight: 8 }}>
            取消
          </Button>
          {mode === ACTIONS.ADD && (
            <Button onClick={handleSubmit} type="primary">
              添加
            </Button>
          )}
          {mode === ACTIONS.EDIT && (
            <Button onClick={handleSubmit} type="primary">
              保存
            </Button>
          )}
        </div>
      )}
      // FIXME 这个配置不生效，visible切换的时候表单没有销毁
      destroyOnClose
    >
      <Form {...layout} form={form} name="position-manage-form">
        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>基本信息</div>
        <Form.Item
          name="name"
          label="岗位名称"
          initialValue={position?.name}
          rules={[
            { required: true },
            { max: 128, transform: transformStringLength, message: '岗位名称超长' },
          ]}
        >
          <Input placeholder="输入岗位名称" disabled={mode === ACTIONS.PREVIEW} />
        </Form.Item>
        <Form.Item name="isPrimary" label="岗位标识" initialValue={position?.isPrimary} rules={[{ required: true }]}>
          <Select
            getPopupContainer={triggerNode => triggerNode.parentNode}
            placeholder="请选择岗位标识"
            disabled={mode === ACTIONS.PREVIEW}
          >
            <Option value={1}>主岗</Option>
            <Option value={0}>非主岗</Option>
          </Select>
        </Form.Item>
        {
          mode === ACTIONS.ADD && (
            <Form.Item
              name="orgId"
              label="组织"
              initialValue={position?.orgId ? [position.orgId] : []}
              rules={[{ required: true }]}
            >
              <TreeSelect
                loadData={handleTreeDataLoad}
                treeData={treeData}
                showCheckedStrategy={TreeSelect.SHOW_ALL}
                placeholder="请选择组织"
                getPopupContainer={triggerNode => triggerNode.parentNode}
                treeCheckStrictly
                treeCheckable
                multiple
              />
            </Form.Item>
          )
        }
        {
          mode === ACTIONS.ADD || ACTIONS.EDIT && (
            <Form.Item name="orgName" label="组织" initialValue={position?.orgName}>
              <Input disabled />
            </Form.Item>
          )
        }
        <Form.Item name="description" label="岗位描述" initialValue={position?.description}>
          <Input.TextArea
            rows={6}
            placeholder="输入岗位描述"
            disabled={mode === ACTIONS.PREVIEW}
            rules={[
              { required: true },
              { max: 255, transform: transformStringLength, message: '岗位描述超长' },
            ]}
          />
        </Form.Item>
        <Form.Item name="dataSource" label="数据来源" initialValue={position?.dataSource || '501'}>
          <Select
            getPopupContainer={triggerNode => triggerNode.parentNode}
            placeholder="请选择数据来源"
            disabled
          >
            {dataSourceEnum.map(item => <Option key={item.code}>{item.name}</Option>)}
          </Select>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default PositionModifyDrawer;
